package com.flower8.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flower8.model.Host;
import com.flower8.model.SysMenu;
import com.flower8.service.SysConfigService;
import com.flower8.service.SysMenuService;
import com.flower8.sysconfig.constants.MsgConstants;
import com.flower8.sysconfig.constants.UserConstants;
import com.flower8.utils.StringUtil;
import com.flower8.utils.UserUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 菜单控制层
 * @Author: tanglin
 * @Date: 2019/09/03 16:11
 * @Version: 1.0
 */
@RestController
@RequestMapping("/sysmenu")
public class SysMenuController extends BaseController{
    private static final Logger log = LoggerFactory.getLogger(SysMenuController.class);

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 初始化加载菜单
     * @return
     */
    @RequestMapping("/menuList")
    public Object permissionsCurrent() {
        logBefore(log, "++++++++++ 查询菜单列表 ++++++++++");
        List<SysMenu> list = sysMenuService.getListByUser(UserUtil.getCurrentUser().getPermission());
        final List<SysMenu> permissions = list.stream().filter(l -> l.getType().equals(1))
                .collect(Collectors.toList());
        //遍历一级菜单
        List<SysMenu> firstLevel = permissions.stream().filter(p -> p.getParentId().equals(0L)).collect(Collectors.toList());
        firstLevel.parallelStream().forEach(p -> {
            setChild(p, permissions);
        });
        setMenuHost(firstLevel);
        Map<String, Object> data = new HashMap<>();
        data.put("menuList", firstLevel);

        return responseResultForSuccess(data);
    }

    /**
     * 设置子元素
     * @param p
     * @param permissions
     */
    private void setChild(SysMenu p, List<SysMenu> permissions) {
        List<SysMenu> child = permissions.parallelStream().filter(a -> a.getParentId().equals(p.getId())).collect(Collectors.toList());
        p.setChild(child);
        if (!CollectionUtils.isEmpty(child)) {
            child.parallelStream().forEach(c -> {
                //递归设置子元素，多级菜单支持
                setChild(c, permissions);
            });
        }
    }

    /**
     * 菜单列表
     * @param pId
     * @param permissionsAll
     * @param list
     */
    private void setMenuListList(Long pId, List<SysMenu> permissionsAll, List<SysMenu> list) {
        for (SysMenu per : permissionsAll) {
            if (per.getParentId().equals(pId)) {
                list.add(per);
                if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
                    setMenuListList(per.getId(), permissionsAll, list);
                }
            }
        }
    }

    /**
     * 查询所有菜单
     * @return
     */
    @RequestMapping("/menuListAll")
    public List<SysMenu> menuList() {
        logBefore(log, "++++++++++ 查询所有菜单列表 ++++++++++");
        List<SysMenu> menuAll = sysMenuService.getMenuAll();

        List<SysMenu> list = Lists.newArrayList();
        setMenuListList(0L, menuAll, list);
        setMenuHost(list);
        return list;
    }

    /**
     * 根据菜单id查询
     * @param id
     * @return
     */
    @RequestMapping("/getMenuById")
    public SysMenu getMenuById(@RequestParam Long id) {
        return sysMenuService.getById(id);
    }

    /**
     * 查询一级菜单
     * @return
     */
    @RequestMapping("/parentMenu")
    public List<SysMenu> parentMenu() {
        List<SysMenu> parents = sysMenuService.listParents();
        return parents;
    }

    /**
     * 查询所有菜单树
     * @return
     */
    @RequestMapping("/all")
    public JSONArray permissionsAll() {
        List<SysMenu> permissionsAll = sysMenuService.getMenuAll();
        JSONArray array = new JSONArray();
        setPermissionsTree(0L, permissionsAll, array);

        return array;
    }

    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(Long pId, List<SysMenu> permissionsAll, JSONArray array) {
        for (SysMenu per : permissionsAll) {
            if (per.getParentId().equals(pId)) {
                String string = JSONObject.toJSONString(per);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(per.getId(), permissionsAll, child);
                }
            }
        }
    }

    /**
     * 新增菜单
     * @param sysMenu
     */
    @RequestMapping("/saveMenu")
    public Object save(@RequestBody SysMenu sysMenu) {
        try {
            sysMenuService.saveMenu(sysMenu);
            return returnSuccessMsg(null,"新增成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return returnFailureMsg("新增失败");
        }
    }

    /**
     * 更新菜单
     * @param sysMenu
     */
    @RequestMapping("/updateMenu")
    public Object update(@RequestBody SysMenu sysMenu) {
        try {
            sysMenuService.updateMenu(sysMenu);
            return returnSuccessMsg(null,"修改成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return returnFailureMsg("修改失败");
        }
    }

    /**
     * 删除菜单
     * @param id
     */
    @RequestMapping("/deleteMenu")
    public Object delete(@RequestParam Long id) {
        Map res = new HashMap();
        try {
            sysMenuService.deleteMenu(id);
            return returnSuccessMsg(null,"删除成功");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return returnFailureMsg("删除失败");
        }
    }

    /**
     * 查询服务器列表
     * @param request
     * @return
     */
    @RequestMapping("/getHostList")
    public Object getHostList(){
        logBefore(log, "++++++++++ 查询服务器 ++++++++++");
        Map res = new HashMap();
        try {
            List<Host> hostList = new ArrayList<>();
            // 默认服务器
            Host hostDefault = new Host();
            hostDefault.setName("主后台服务器");
            hostDefault.setHost("");
            hostList.add(hostDefault);
            // 账单服务器
            String billAdminHost = getBillAdminHost();
            if (!StringUtil.isEmptyAfterTrim(billAdminHost)) {
                Host hostBillAdmin = new Host();
                hostBillAdmin.setName("账单后台服务器");
                hostBillAdmin.setHost("billAdminHost");
                hostList.add(hostBillAdmin);
            }
            res.put("hostList", hostList);
            logAfter(log);
            return responseResultForSuccess(res);
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return responseResultForError(MsgConstants.ERROR_99001_MSG);
        }
    }

    private void setMenuHost(List<SysMenu> list) {
        setMenuHost(list, null);
    }

    private void setMenuHost(List<SysMenu> list, Map<String, String> hosts) {
        if (hosts == null) {
            hosts = getHosts();
        }
        for (int i = 0; i < list.size(); i++) {
            SysMenu sysMenu = list.get(i);
            String host = sysMenu.getHost();
            if ("billAdminHost".equals(host)) {
                if (!StringUtil.isEmptyAfterTrim(hosts.get("billAdminHost"))) {
                    host = hosts.get("billAdminHost");
                } else {
                    host = "";
                }
            } else {
                host = "";
            }
            sysMenu.setHost(host);
            List<SysMenu> child = sysMenu.getChild();
            if (child != null && child.size() > 0) {
                setMenuHost(child, hosts);
            }
        }
    }

    private Map<String, String> getHosts() {
        Map<String, String> hosts = new HashMap<>();
        //账单服务器
        String billAdminHost = getBillAdminHost();
        if (!StringUtil.isEmptyAfterTrim(billAdminHost)) {
            hosts.put("billAdminHost", billAdminHost);
        }

        return hosts;
    }

	/**
	 * 
	 * @return
	 */
	private String getBillAdminHost() {
		String host = "";
		try {
			Map result = sysConfigService.getSysDist("billAdminHost");
			if (!result.isEmpty()) {
				host = result.get("billAdminHost").toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return host;
	}

}
